package com.wocai.jrt.orgadmin.employee.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.multipart.MultipartFile;

import com.vteba.common.exception.ServiceException;
import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.utils.id.ObjectId;
import com.wocai.jrt.admin.common.cache.Const;
import com.wocai.jrt.admin.user.model.Roles;
import com.wocai.jrt.admin.user.model.UserRole;
import com.wocai.jrt.admin.user.service.spi.UserRoleService;
import com.wocai.jrt.orgadmin.device.service.spi.PosPadService;
import com.wocai.jrt.orgadmin.employee.bean.EmployeeDetailResBean;
import com.wocai.jrt.orgadmin.employee.dao.EmployeeDao;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.model.EmployeeBean;
import com.wocai.jrt.orgadmin.employee.model.EmployeeGroup;
import com.wocai.jrt.orgadmin.employee.model.GroupMember;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeGroupService;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.employee.service.spi.GroupMemberService;
import com.wocai.jrt.orgadmin.stats.bean.EmpStatsMapperReqBean;
import com.wocai.jrt.orgadmin.stats.bean.EmpStatsResBean;
import com.wocai.jrt.orgadmin.stats.bean.EmployeeDataSum;
import com.wocai.jrt.orgadmin.stats.bean.IndexStatsReqBean;
import com.wocai.jrt.orgadmin.stats.bean.TopFive;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 员工相关的service业务实现。
 * 
 * @author yinlei
 * @date 2015-8-4 15:49:29
 */
@Named
public class EmployeeServiceImpl extends MyBatisServiceImpl<Employee, EmployeeBean, String>
		implements EmployeeService {
	private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeServiceImpl.class);

	// 添加了方法后，记得改为private
	protected EmployeeDao employeeDao;

	@Inject
	private PasswordEncoder bcryptPasswordEncoder;

	@Inject
	private UserRoleService userRoleServiceImpl;

	@Inject
	private PosPadService posPadServiceImpl;
	@Inject
	private GroupMemberService groupMemberServiceImpl;
	@Inject
	private EmployeeGroupService employeeGroupServiceImpl;

	@Override
	@Inject
	public void setBaseDao(BaseDao<Employee, EmployeeBean, String> employeeDao) {
		this.baseDao = employeeDao;
		this.employeeDao = (EmployeeDao) employeeDao;
	}

	@Override
	public int saveEmployee(Employee employee) {
		int result = 0;
		try {
			employee.setEmployeeId(ObjectId.get().toString());
			employee.setLoginPwd(bcryptPasswordEncoder.encode(employee.getLoginPwd()));
			employee.setWorkPwd(bcryptPasswordEncoder.encode(employee.getWorkPwd()));
			employee.setOrgCode(UserUtils.getOrgCode());
			employee.setOrgId(UserUtils.getOrgId());

			EmployeeGroup employeeGroup = employeeGroupServiceImpl.get(employee.getDeptId());
			if (null == employeeGroup) {
				result = 3;// 没有该部门
				return result;
			}
			employee.setDepartment(employeeGroup.getGroupName());
			// 部门员工数+1
			EmployeeGroup employeeGroupUpdata = new EmployeeGroup();
			employeeGroupUpdata.setId(employee.getDeptId());
			int menberNumber = employeeGroup.getMemberNumber();
			employeeGroupUpdata.setMemberNumber(menberNumber + 1);
			employeeGroupServiceImpl.updateById(employeeGroupUpdata);
			// 部门员工 +1
			GroupMember groupMember = new GroupMember();
			groupMember.setGroupId(employee.getDeptId());
			groupMember.setEmployeeId(employee.getEmployeeId());
			groupMember.setId(ObjectId.get().toString());
			groupMemberServiceImpl.save(groupMember);

			int ret = save(employee);
			if (ret == 1) {
				result = 1;
			} else {
				LOGGER.warn("save Employee error.");
			}
		} catch (Exception e) {
			LOGGER.error("save employee error, msg=[{}].", e.getMessage());
			throw new ServiceException("save Employee error.", e);
		}
		return result;
	}

	@SuppressWarnings("unused")
	private int saveFile(Employee employee) {
		int result = 0;
		try {
			MultipartFile multipartFile = employee.getFile();
			if (multipartFile != null) {
				File file = new File(employee.getFilePath());
				if (!file.exists()) {
					file.createNewFile();
				} else {
					file.delete();
				}
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(multipartFile.getBytes());
				fos.flush();
				IOUtils.closeQuietly(fos);
				result = 1;
			}
		} catch (Exception e) {
			LOGGER.error("save Employee avatar error, msg=[{}].", e.getMessage());
			result = 2;
		}
		return result;
	}

	@Override
	public int updateEmployee(Employee employee) {
		int result = 0;
		try {
			String id = employee.getId();
			Employee oldEmployee = employeeDao.get(id);
			if (oldEmployee == null) {
				result = 4;// 没有该员工
				return result;
			}
			// 更新部门
			if (null != employee.getDeptId()) {
				if (employee.getDeptId().equals(oldEmployee.getDeptId())) {
					// 部门没有改变，不用更新
					employee.setDeptId(null);
					employee.setDepartment(null);
				} else {
					// 部门改变，更新部门信息
					EmployeeGroup newEmployeeGroup = employeeGroupServiceImpl.get(employee
							.getDeptId());
					if (null != newEmployeeGroup) {
						// group_member
						GroupMember odlGroupMember = new GroupMember();
						odlGroupMember.setEmployeeId(id);
						groupMemberServiceImpl.deleteBulks(odlGroupMember);

						GroupMember newGroupMember = new GroupMember();
						newGroupMember.setGroupId(employee.getDeptId());
						newGroupMember.setEmployeeId(id);
						newGroupMember.setId(ObjectId.get().toString());
						groupMemberServiceImpl.save(newGroupMember);

						employee.setDeptId(newEmployeeGroup.getId());
						employee.setDepartment(newEmployeeGroup.getGroupName());
						// 有可能之前是部门负责人
						EmployeeGroup employeeGroupOld = new EmployeeGroup();
						employeeGroupOld.setEmployeeId(employee.getEmployeeId());
						EmployeeGroup employeeGroupNew = new EmployeeGroup();
						employeeGroupNew.setEmployeeId("");
						employeeGroupNew.setEmployeeName("");
						employeeGroupServiceImpl.updateBulks(employeeGroupNew, employeeGroupOld);
					} else {
						employee.setDeptId(null);
						employee.setDepartment(null);
					}
				}
			}
			// 更新员工信息
			int j = employeeDao.updateById(employee);
			if (j == 1) {
				result = 1;
			}

		} catch (Exception e) {
			LOGGER.error("update employee error, msg=[{}].", e.getMessage());
			throw new ServiceException("update Employee error.", e);
		}
		return result;
	}

	@Override
	public int setUserRole(Employee employee) {
		String employeeId = employee.getEmployeeId();
		try {
			// 1、删除原有的关系
			deleteUserRole(employeeId);

			String roleIds = employee.getRoleIds();
			if (StringUtils.isNotBlank(roleIds)) {
				// 2、维护角色和权限的新关联
				saveUserRole(employeeId, roleIds);
			}
		} catch (Exception e) {
			LOGGER.error("update user's role error, msg=[{}].", e.getMessage());
			throw new ServiceException("update user's role error", e);
		}

		return 1;
	}

	/**
	 * 保存用户角色的关联关系
	 * 
	 * @param id
	 *            用户Id
	 * @param roleIds
	 *            该用户的角色Id
	 */
	private void saveUserRole(String id, String roleIds) {
		LOGGER.info("role's ids=[{}]", roleIds);
		String[] roles = StringUtils.split(roleIds, ",");
		for (String roleId : roles) {
			if (roleId.length() < Const.ID_LEN) {
				continue;
			}

			UserRole userRole = new UserRole();
			userRole.setId(ObjectId.get().toString());
			userRole.setUserId(id);
			userRole.setRoleId(roleId);
			// 保存关联关系
			int ret = userRoleServiceImpl.save(userRole);
			if (ret <= 0) {
				LOGGER.error("user and role's relation error.");
				throw new ServiceException("user and role's relation error.");
			}
		}
	}

	/**
	 * 根据用户id删除，用户和角色的关联
	 * 
	 * @param userId
	 *            用户id
	 * @return 删除记录的条数
	 */
	private int deleteUserRole(String userId) {
		UserRole userRole = new UserRole();
		userRole.setUserId(userId);
		int ret = userRoleServiceImpl.deleteBulks(userRole);
		return ret;
	}

	@Override
	public int updateInfo(Employee employee) {
		try {
			int state = employee.getState();
			employee.setState(null);
			int result = updateById(employee);
			if (result <= 0) {
				LOGGER.warn("updateInfo's record is zero.");
				return 0;
			} else if (result == 1 && state == 1) { // 员工信息更新成功，且是回收设备
				int ret = posPadServiceImpl.pullbackDevice(employee.getPosPadId());
				if (ret <= 0) {
					String msg = "Employee update successfully, PosPad update error.";
					LOGGER.error(msg);
					throw new ServiceException(msg);
				}
			}
		} catch (Exception e) {
			LOGGER.error("updateInfo error, msg=[{}].", e.getMessage());
			throw new ServiceException("updateInfo error.");
		}
		return 1;
	}

	@Override
	public EmployeeDetailResBean getEmployeeDetailResBean(String userId) {
		return employeeDao.getEmployeeDetailResBean(userId);
	}

	@Override
	public List<Roles> queryUserRoles(List<String> userIds) {
		return employeeDao.queryUserRoles(userIds);
	}

	@Override
	public List<EmpStatsResBean> queryAllPlanner(EmpStatsMapperReqBean bean) {
		return employeeDao.queryAllPlanner(bean);
	}

	@Override
	public List<TopFive> employeeTopFive(IndexStatsReqBean indexStatsReqBean) {
		return employeeDao.employeeTopFive(indexStatsReqBean);
	}

	@Override
	public List<TopFive> employeeGroupTopFive(IndexStatsReqBean indexStatsReqBean) {
		return employeeDao.employeeGroupTopFive(indexStatsReqBean);
	}

	@Override
	public List<EmployeeDataSum> employeeDataSum(IndexStatsReqBean indexStatsReqBean) {
		return employeeDao.employeeDataSum(indexStatsReqBean);
	}

	@Override
	public List<EmployeeDataSum> groupDataSum(IndexStatsReqBean indexStatsReqBean) {
		return employeeDao.groupDataSum(indexStatsReqBean);
	}

	@Override
	public List<Employee> getGroupEmploee(String id) {
		return employeeDao.getGroupEmploee(id);
	}

	@Override
	public int deleteEmployee(Employee employee) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int leave(Employee employee) {
		int result = 0;
		try {
			if (null != employee.getDeptId()) {
				// 删除部门
				GroupMember groupMember = new GroupMember();
				groupMember.setEmployeeId(employee.getEmployeeId());
				groupMemberServiceImpl.deleteBulks(groupMember);
				// 有可能是部门负责人
				EmployeeGroup employeeGroupOld = new EmployeeGroup();
				employeeGroupOld.setEmployeeId(employee.getEmployeeId());
				EmployeeGroup employeeGroupNew = new EmployeeGroup();
				employeeGroupNew.setEmployeeId("");
				employeeGroupNew.setEmployeeName("");
				employeeGroupServiceImpl.updateBulks(employeeGroupNew, employeeGroupOld);
			}
			// 自己的部门删掉
			Employee employeeUpdata = new Employee();
			employeeUpdata.setEmployeeId(employee.getEmployeeId());
			employeeUpdata.setDepartment("");
			employeeUpdata.setDeptId("");
			employeeUpdata.setState(0);
			result = employeeDao.updateById(employeeUpdata);
		} catch (Exception e) {
			throw new ServiceException("离职失败！", e);
		}
		return result;
	}
}
